﻿#include "page4.h"
#include "mainwindow.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTableView>
#include <QLabel>
#include <QPixmap>
#include <QPalette>
#include <QLayout>
#include <QVBoxLayout>
#include <QMap>
#include <QPair>
#include <QDate>
#include <QSqlRecord>
#include <QSqlField>
#include <QtCharts/QChartView>
#include <QtCharts/QBarSeries>
#include <QtCharts/QBarSet>
#include <QtCharts/QBarCategoryAxis>
#include <QtCharts/QValueAxis>
#include "databaseManager.h"
#include <QList>

Page4::Page4(QWidget *parent) :
    QWidget(parent),
    mainLayout(new QVBoxLayout(this)),
    chartView(nullptr)
{
    // 设置窗口大小
    setFixedSize(1280, 720);
    //设置背景
    QPixmap background(":new/prefix1/bg.jpg");
    QLabel* backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(background.scaled(this->size())); // 缩放背景图片以适应窗口大小

    backgroundLabel->setGeometry(0, 0, this->width(), this->height());
    backgroundLabel->lower();

    // 设置按钮的初始Y轴位置
    int yPos = 222;

    // Assuming you have a QIcon object created from your image file
    QIcon icon1(":new/prefix1/order.jpg");
    QIcon icon11(":new/prefix1/order2.jpg");
    // Create the QPushButton and set its properties
    orderButton = new QPushButton(this);
    orderButton->setIcon(icon1);  // Set the icon
    orderButton->setIconSize(QSize(260, 71));  // Set the icon size
    orderButton->setFlat(true);  // Make the button flat (no background)
    orderButton->setFixedSize(260, 71);  // Set the fixed size of the button
    orderButton->setGeometry(1, yPos, 260, 71);
    connect(orderButton, &QPushButton::clicked, this, [this](){
        emit orderRequested();
    });
    connect(orderButton, &QPushButton::pressed, this, [this, icon11]() {
        orderButton->setIcon(icon11);  // Change to icon10 when pressed
    });

    connect(orderButton, &QPushButton::released, this, [this, icon1]() {
        orderButton->setIcon(icon1);  // Revert to icon1 when released
        emit orderRequested();  // Emit the signal after the button is released
    });

    // 调整下一个按钮的Y轴位置
    yPos += 68;

    // 创建并设置生产按钮
    QIcon icon2(":new/prefix1/production.jpg");
    QIcon icon12(":new/prefix1/production2.jpg");
    productionButton = new QPushButton("", this);
    productionButton->setIcon(icon12);  // Set the icon
    productionButton->setIconSize(QSize(260, 71));  // Set the icon size
    productionButton->setFlat(true);  // Make the button flat (no background)
    productionButton->setFixedSize(260, 71);  // Set the fixed size of the button
    productionButton->setGeometry(1, yPos, 260, 71);
    connect(productionButton, &QPushButton::clicked, this, [this]() {
        emit productionRequested();
    });
    connect(productionButton, &QPushButton::pressed, this, [this, icon2]() {
        productionButton->setIcon(icon2);
    });

    connect(productionButton, &QPushButton::released, this, [this, icon12]() {
        productionButton->setIcon(icon12);
        emit productionRequested();  // Emit the signal after the button is released
    });

    // 调整下一个按钮的Y轴位置
    yPos += 68;

    // 创建并设置财务按钮
    QIcon icon3(":new/prefix1/finance.jpg");
    QIcon icon13(":new/prefix1/finance2.jpg");
    financeButton = new QPushButton("", this);
    financeButton->setIcon(icon3);  // Set the icon
    financeButton->setIconSize(QSize(260, 71));  // Set the icon size
    financeButton->setFlat(true);  // Make the button flat (no background)
    financeButton->setFixedSize(260, 71);  // Set the fixed size of the button
    financeButton->setGeometry(1, yPos, 260, 71);
    connect(financeButton, &QPushButton::clicked, this, [this]() {
        emit financeRequested();
    });
    connect(financeButton, &QPushButton::pressed, this, [this, icon13]() {
        financeButton->setIcon(icon13);
    });

    connect(financeButton, &QPushButton::released, this, [this, icon3]() {
        financeButton->setIcon(icon3);
        emit financeRequested();  // Emit the signal after the button is released
    });


    // 调整下一个按钮的Y轴位置
    yPos += 68;

    // 创建并设置库存按钮
    QIcon icon4(":new/prefix1/warehouse.jpg");
    QIcon icon14(":new/prefix1/warehouse2.jpg");
    warehouseButton = new QPushButton("", this);
    warehouseButton->setIcon(icon4);  // Set the icon
    warehouseButton->setIconSize(QSize(260, 71));  // Set the icon size
    warehouseButton->setFlat(true);  // Make the button flat (no background)
    warehouseButton->setFixedSize(260, 71);  // Set the fixed size of the button
    warehouseButton->setGeometry(1, yPos, 260, 71);
    connect(warehouseButton, &QPushButton::clicked, this, [this]() {
        emit storeRequested();
    });
    connect(warehouseButton, &QPushButton::pressed, this, [this, icon14]() {
        warehouseButton->setIcon(icon14);
    });

    connect(warehouseButton, &QPushButton::released, this, [this, icon4]() {
        warehouseButton->setIcon(icon4);
        emit storeRequested();  // Emit the signal after the button is released
    });

    // Create the table view in the center
    tableView = new QTableView(this);
    tableView->setGeometry(265,135, 1010,590);  // Adjusted for 1280x720 screen size

    // Create the production progress label
    productionProgressLabel = new QLabel("     ", this);
    productionProgressLabel->setAlignment(Qt::AlignCenter);
    productionProgressLabel->setGeometry(640, 10, 200, 50);  // Adjusted for 1280x720 screen size

    emptyButton = new QPushButton(u8"", this);
    emptyButton->setGeometry(265,60,1023,75); // 调整此位置以适应屏幕
    emptyButton->setStyleSheet("QPushButton {"
                             " border: none; "
                             "background-image: url(:new/prefix1/shengchanjindu.jpg); "
                             "background-repeat: no-repeat; "
                             "background-position: center; }");

    // 创建返回按钮
        frontButton = new QPushButton(u8"", this);
        frontButton->setGeometry(1050,0,170,55); // 调整此位置以适应屏幕
        frontButton->setStyleSheet("QPushButton {"
                                 " border: none; "
                                 "background-image: url(:new/prefix1/tuichudenglu.jpg); "
                                 "background-repeat: no-repeat; "
                                 "background-position: center; }");


        connect(frontButton, &QPushButton::pressed, this, [this]() {
            frontButton->setStyleSheet("QPushButton {"
                                     " border: none; "
                                     "background-image: url(:/new/prefix1/tuichudenglu2.jpg); "
                                     "background-repeat: no-repeat; "
                                     "background-position: center; }");
        });
        connect(frontButton, &QPushButton::released, this, [this]() {
            frontButton->setStyleSheet("QPushButton {"
                                     " border: none; "
                                     "background-image: url(:/new/prefix1/tuichudenglu.jpg); "
                                     "background-repeat: no-repeat; "
                                     "background-position: center; }");
        });

   connect(frontButton, &QPushButton::clicked, this, &Page4::onFrontButtonClicked);
   QVBoxLayout* backLayout = new QVBoxLayout(this);
   setLayout(backLayout);

    yPos += 68;
    QIcon icon6(":new/prefix1/operationGuide.jpg");
    QIcon icon16(":new/prefix1/operationGuide2.jpg");
    helpButton = new QPushButton("", this);
    helpButton->setIcon(icon6);  // Set the icon
    helpButton->setIconSize(QSize(260, 71));  // Set the icon size
    helpButton->setFlat(true);  // Make the button flat (no background)
    helpButton->setFixedSize(260, 71);  // Set the fixed size of the button
    helpButton->setGeometry(1, yPos, 260, 71);
    //连接按钮
         yPos += 68;
        QIcon icon7(":new/prefix1/connect.jpg");
        QIcon icon17(":new/prefix1/connect2.jpg");
        connectButton = new QPushButton("", this);
        connectButton->setIcon(icon7);  // Set the icon
        connectButton->setIconSize(QSize(260, 71));  // Set the icon size
        connectButton->setFlat(true);  // Make the button flat (no background)
        connectButton->setFixedSize(260, 71);  // Set the fixed size of the button
        connectButton->setGeometry(1, yPos, 260, 71);

        connect(connectButton, &QPushButton::clicked, this, [this]() {
            emit pageRequested13();
        });


        yPos += 68;

        // 创建并设置添加员工按钮
        QIcon icon5(":new/prefix1/tianjiayuangong01.jpg");
        QIcon icon15(":new/prefix1/tianjiayuangong02.jpg");
        addEmployeeButton = new QPushButton("", this);
        addEmployeeButton->setIcon(icon5);  // Set the icon
        addEmployeeButton->setIconSize(QSize(260, 71));  // Set the icon size
        addEmployeeButton->setFlat(true);  // Make the button flat (no background)
        addEmployeeButton->setFixedSize(260, 71);  // Set the fixed size of the button
        addEmployeeButton->setGeometry(1, yPos, 260, 71);
        connect(addEmployeeButton, &QPushButton::clicked, this, [this]() {
            emit addEmployeeRequested();
        });



        connect(connectButton, &QPushButton::pressed, this, [this, icon17]() {
             connectButton->setIcon(icon17);
        });
        connect(connectButton, &QPushButton::released, this, [this, icon7]() {
            connectButton->setIcon(icon7);
            emit pageRequested13();  // Emit the signal after the button is released
        });


    connect(helpButton, &QPushButton::clicked, this, [this]() {
        emit pageRequested10();
    });

    connect(helpButton, &QPushButton::pressed, this, [this, icon16]() {
         helpButton->setIcon(icon16);
    });
    connect(helpButton, &QPushButton::released, this, [this, icon6]() {
        helpButton->setIcon(icon6);
        emit pageRequested10();  // Emit the signal after the button is released
    });
    setLayout(mainLayout);
}

void Page4::financeHide()
{
    financeButton->hide();
}

Page4::~Page4()
{
    delete chart;
    delete chartView;
}

void Page4::clearOldChart()
{
    if (chartView) {
        mainLayout->removeWidget(chartView);
        delete chartView;
        chartView = nullptr;
    }
}

int Page4::getQuarterFromDate(const QDate &date) {
    int month = date.month();
    return (month - 1) / 3 + 1;
}

QString getChineseQuarter(int quarter)
{
    switch (quarter) {
    case 1:
        return "一季度";
    case 2:
        return "二季度";
    case 3:
        return "三季度";
    case 4:
        return "四季度";
    default:
        return "未知季度";
    }
}

void Page4::generateQuarterlyReport()
{
    // 清除旧的图表视图
    clearOldChart();

    // 获取日期和状态数据模型
    DatabaseManager &dbManager = DatabaseManager::instance();
    QList<QPair<QString, QString>> dateAndConditionList = dbManager.getPurchaseOrderDateAndCondition();

    // 用于存储季度统计数据
    QMap<QString, QPair<int, int>> quarterlyData; // key: "YYYY-Qn", value: <未完成订单数, 已完成订单数>

    // 遍历日期和状态数据
    for (const auto &pair : dateAndConditionList) {
        QString dateString = pair.first;
        QString condition = pair.second;

        // 将字符串日期转换为 QDate 类型
        QDate acceptDate = QDate::fromString(dateString, "yyyy-MM-dd");

        // 检查日期是否有效，如果无效则跳过该记录
        if (!acceptDate.isValid()) {
            //qDEbug() << "Invalid date format:" << dateString;
            continue;
        }

        // 计算季度
        int year = acceptDate.year();
        int quarter = getQuarterFromDate(acceptDate);
        QString key = QString("%1-Q%2").arg(year).arg(quarter);

        // 更新统计数据
        if (!quarterlyData.contains(key)) {
            quarterlyData[key] = qMakePair(0, 0);
        }

        if (condition == "未完成") {
            quarterlyData[key].first++;
        } else if (condition =="已完成") {
            quarterlyData[key].second++;
        }
    }

    // 创建柱状图数据集
    QBarSeries *series = new QBarSeries();

    // 设置所有季度名称列表
    QStringList categories = {"一季度", "二季度", "三季度", "四季度"};

    // 创建四个季度的数据集
    QBarSet *setIncomplete = new QBarSet("未完成");
    QBarSet *setComplete = new QBarSet("已完成");

    for (int i = 1; i <= 4; ++i) {
        QString key = QString("%1-Q%2").arg(QDate::currentDate().year()).arg(i);
        if (quarterlyData.contains(key)) {
            *setIncomplete << quarterlyData[key].first;
            *setComplete << quarterlyData[key].second;
        } else {
            *setIncomplete << 0;
            *setComplete << 0;
        }
    }

    // 将数据集添加到系列中
    series->append(setIncomplete);
    series->append(setComplete);

    // 创建柱状图
    QChart *chart = new QChart();
    chart->addSeries(series);
    chart->setTitle("订单完成情况");
    chart->setAnimationOptions(QChart::AllAnimations);

    // 设置X轴（季度）
    QBarCategoryAxis *axisX = new QBarCategoryAxis();
    axisX->append(categories);
    chart->addAxis(axisX, Qt::AlignBottom);
    series->attachAxis(axisX);

    // 设置Y轴（订单数量）
    QValueAxis *axisY = new QValueAxis();
    axisY->setRange(0, 5); // 根据实际数据调整范围
    chart->addAxis(axisY, Qt::AlignLeft);
    series->attachAxis(axisY);

    // 设置图例
    chart->legend()->setVisible(true);
    chart->legend()->setAlignment(Qt::AlignBottom);

    // 设置柱状图的颜色和间隔
    setIncomplete->setColor(QColor(169, 169, 169)); // 灰色代表未完成订单
    setComplete->setColor(QColor(0, 0, 255));       // 蓝色代表已完成订单

    // 创建图表视图
    chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);
    // 设置布局

       mainLayout->setContentsMargins(265, 135, 0, 0); // 设置外边距以控制图表位置
    // 添加图表视图到布局
    mainLayout->addWidget(chartView);
}

void Page4::signuphide() {
    addEmployeeButton->hide();
}
void Page4::onFrontButtonClicked()
{
    QMessageBox msgBox;
    msgBox.setText("确定退出登录吗?");
    msgBox. setWindowTitle("退出登录");
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.button(QMessageBox::Ok)->setText("确认");
    msgBox.button(QMessageBox::Cancel)->setText("取消");
    msgBox.setStyleSheet(
        "QMessageBox {"
        "  background-color: #FFFFFF;"
        "}"
        "QMessageBox QLabel {"
        "  font-size: 18px;"
        "  font-weight: bold;"
        "  color: black;"
        "}"
        "QMessageBox QPushButton {"
        "  font-size: 18px;"
        "  font-weight: bold;"
        "  border: 2px solid #E0E0E0;"
        "  border-radius: 20px;"
        "  padding: 10px;"
        "  background-color: #0093D1;"
        "  color: white;"
        "}"
    );

    if (msgBox.exec() == QMessageBox::Ok) {
        emit pageRequested1();
    }
}
